const chessboard = document.querySelector('.chessboard');
const boardSize = 15;
let board = Array(boardSize).fill().map(() => Array(boardSize).fill(null));
let currentPlayer = 'black'; // 黑子先手

// 绘制棋盘
function drawBoard() {
    for (let i = 0; i < boardSize; i++) {
        for (let j = 0; j < boardSize; j++) {
            const cell = document.createElement('div');
            cell.classList.add('cell');
            cell.setAttribute('data-x', i);
            cell.setAttribute('data-y', j);
            cell.style.gridColumn = j + 1;
            cell.style.gridRow = i + 1;
            chessboard.appendChild(cell);
        }
    }
}

// 放置棋子
function placeChessman(x, y) {
    const cell = document.querySelector(`[data-x="${x}"][data-y="${y}"]`);
    if (cell && board[x][y] === null) {
        const chessman = document.createElement('div');
        chessman.classList.add('chessman', currentPlayer);
        cell.appendChild(chessman);
        board[x][y] = currentPlayer;
        if (checkWin(x, y, currentPlayer)) {
            alert(`玩家 ${{ "black": "黑方", "white": "白方" }[currentPlayer]} 获胜!`);
        }
        disableCell(cell);
        switchPlayer();
    }
}

/**
 * 清空棋盘
 */
function clearBoard() {
    // 清空棋盘的HTML元素
    chessboard.innerHTML = '';
    // 重新初始化棋盘状态
    board = Array(boardSize).fill().map(() => Array(boardSize).fill(null));
    // 重新绘制棋盘
    drawBoard();
}

// 检查胜负
function checkWin(x, y, color) {
    // 这里需要实现检查是否五子连珠的逻辑
    // 检查水平、垂直、对角线方向
    const directions = [
        [0, 1], [1, 0], // 右和下
        [0, -1], [-1, 0], // 左和上
        [1, 1], [-1, -1], // 右下和左上
        [1, -1], [-1, 1] // 右上和左下
    ];
    const countInDirection = (dx, dy) => {
        let count = 1; // 已经确定的一个棋子
        let nx = x + dx, ny = y + dy;
        while (nx >= 0 && nx < boardSize && ny >= 0 && ny < boardSize &&
            board[nx][ny] === color) {
            count++;
            nx += dx;
            ny += dy;
        }
        nx = x - dx, ny = y - dy; // 检查另一端
        while (nx >= 0 && nx < boardSize && ny >= 0 && ny < boardSize &&
            board[nx][ny] === color) {
            count++;
            nx -= dx;
            ny -= dy;
        }
        return count;
    };

    for (let [dx, dy] of directions) {
        if (countInDirection(dx, dy) >= 5) {
            return true; // 发现五子连珠
        }
    }
    return false;
}

// 切换玩家
function switchPlayer() {
    currentPlayer = currentPlayer === 'black' ? 'white' : 'black';
}

// 禁用单元格
function disableCell(cell) {
    cell.classList.add('disabled');
}

// 事件监听
chessboard.addEventListener('click', function (event) {
    if (event.target.classList.contains('cell') && !event.target.classList.contains('disabled')) {
        const x = parseInt(event.target.getAttribute('data-x'));
        const y = parseInt(event.target.getAttribute('data-y'));
        placeChessman(x, y);
    }
});

drawBoard();